import { useState, useEffect } from 'react';
import { Modal, Form, Radio, InputNumber, Select, TimePicker, Button } from 'antd';
import { PlusCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import moment from 'moment';
import { uuid } from '@inbiz/utils';
import './style.less';

export default function Strategy(props: any) {
    const { modalParams, value, onChange } = props;
    const [form] = Form.useForm();
    const msgTypeData = Form.useWatch('msgType', form);

    const onCancel = () => {
        modalParams?.onCancel && modalParams?.onCancel();
    };

    const onSave = () => {
        onChange(form.getFieldsValue());
        onCancel();
    };

    // const onValuesChange = (_value: any) => {
    //     if (_value?.msgType == 'regular') {
    //         onChange({
    //             ...value,
    //             pushRule: [{
    //                 elementId: uuid(20, 60),
    //                 date: '00:00',
    //                 unit: '0',
    //             }]
    //         });
    //     };
    //     if (_value?.msgType == 'interval') {
    //         onChange({
    //             ...value,
    //             pushRule: {
    //                 reminderTime: '1',
    //                 unit: '0',
    //             }
    //         });
    //     };
    // };

    useEffect(() => {
        form.setFieldsValue(value ? typeof value == 'string' ? JSON.parse(value) : value : {});
    }, [value]);

    return (
        <Modal
            {...modalParams}
            title={'超时通知策略'}
            bodyStyle={{
                padding: '10px 20px 20px 20px',
                maxHeight: document.body.clientHeight * 0.7,
                overflow: 'auto',
            }}
        >
            <Form
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 19 }}
                labelAlign='right'
                labelWrap={true}
                layout={'horizontal'}
                form={form}
            // onValuesChange={onValuesChange}
            >
                <Form.Item label='通知类型' name='msgType'>
                    <Radio.Group>
                        <Radio value={'interval'}>间隔通知</Radio>
                        <Radio value={'regular'}>定时通知</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item label='通知规则' name='msgRule'>
                    <NoticeRule msgTypeData={msgTypeData} />
                </Form.Item>
                <Form.Item label='推送周期' name='pushRule'>
                    <PushCycle msgTypeData={msgTypeData} />
                </Form.Item>
            </Form>
            <div className='process-designer-strategy-footer'>
                <Button type='primary' onClick={onSave}>确定</Button>
                <Button onClick={onCancel}>取消</Button>
            </div>
        </Modal>
    );
};

function NoticeRule(props: any) {
    const { msgTypeData, value, onChange } = props;

    const onTimeChange = (reminderTime: any) => {
        onChange({ ...value, reminderTime })
    };

    const onUnitChange = (unit: any) => {
        onChange({ ...value, unit, })
    }

    return (
        <div className='process-designer-strategy-notice-rule'>
            当流程到达审批节点，
            <InputNumber min={0} onChange={onTimeChange} value={value?.reminderTime} />
            <Select
                options={[
                    {
                        value: '0',
                        label: '法定工作日',
                    },
                    {
                        value: '1',
                        label: '自然日',
                    },
                    {
                        value: '2',
                        label: '小时',
                    },
                ]}
                getPopupContainer={() => document.body}
                onChange={onUnitChange}
                value={value?.unit}
            />
            <span>未处理时，</span>
            <span style={{ marginTop: 10 }}>
                {
                    msgTypeData == 'regular'
                        ?
                        '按推送周期发送催办通知。'
                        :
                        '立即发送催办通知。'
                }
            </span>
        </div>
    )
};

function PushCycle(props: any) {
    const { msgTypeData, value, onChange } = props;

    const onTimeChange = (reminderTime: any) => {
        onChange({ ...value, reminderTime })
    };

    const onUnitChange = (unit: any) => {
        onChange({ ...value, unit, })
    };

    return (
        <>
            {
                msgTypeData == 'regular'
                    ?
                    <CycleRegular value={value} onChange={onChange} />
                    :
                    <div className='process-designer-strategy-push-cycle-interval'>
                        每间隔
                        <InputNumber min={0} onChange={onTimeChange} value={value instanceof Array ? 1 : value?.reminderTime} />
                        <Select
                            options={[
                                {
                                    value: '0',
                                    label: '法定工作日',
                                },
                                {
                                    value: '1',
                                    label: '自然日',
                                },
                                {
                                    value: '2',
                                    label: '小时',
                                },
                            ]}
                            getPopupContainer={() => document.body}
                            onChange={onUnitChange}
                            value={value instanceof Array ? '0' : value?.unit}
                        />
                        <span >重复通知。</span>
                    </div>
            }
            <div style={{ color: '#999' }}>注：法定工作日可能存在些许偏差。</div>
        </>
    )
};

function CycleRegular(props: any) {
    const { value, onChange } = props;
    const [cycleData, setCycleData] = useState<any>();

    const onTimeChange = (_date: any, elementId: string | number) => {
        let _cycleData = [...cycleData];
        const date = moment(_date).format('HH:mm');
        _cycleData = _cycleData?.map((item) => {
            if (item?.elementId == elementId) {
                return {
                    ...item,
                    date,
                }
            } else {
                return item;
            };
        });
        setCycleData(_cycleData);
        onChange(_cycleData);
    };

    const onModeChange = (unit: string, elementId: string | number) => {
        let _cycleData = [...cycleData];
        _cycleData = _cycleData?.map((item, i) => {
            if (item?.elementId == elementId) {
                return {
                    ...item,
                    unit,
                };
            } else {
                return item;
            };
        });
        setCycleData(_cycleData);
        onChange(_cycleData);
    };

    const onAdd = (index: number) => {
        let _cycleData = [...cycleData];
        _cycleData?.splice(index + 1, 0, {
            elementId: uuid(20, 60),
            date: '00:00',
            unit: '0',
        });
        setCycleData(_cycleData);
        onChange(_cycleData);
    };

    const onDelete = (elementId: string) => {
        if (cycleData?.length == 1) {
            return;
        };
        let _cycleData = [...cycleData];
        _cycleData = _cycleData?.filter((item) => item?.elementId != elementId);
        setCycleData(_cycleData);
        onChange(_cycleData);
    };

    useEffect(() => {
        const data = value instanceof Array ? value : [{
            elementId: uuid(20, 60),
            date: '00:00',
            unit: '0',
        },];
        setCycleData(data);
        onChange(data);
    }, []);

    return (
        <div className='process-designer-strategy-push-cycle-regular'>
            {
                cycleData?.map((item, index) => {
                    return (
                        <div className='process-designer-strategy-push-cycle-regular-item' key={item?.elementId}>
                            <TimePicker
                                format='HH:mm'
                                value={moment(item?.date, 'HH:mm')}
                                showNow={false}
                                allowClear={false}
                                onChange={(time: any) => { onTimeChange(time, item?.elementId) }}
                                getPopupContainer={() => document.body}
                            />
                            <Select
                                options={[
                                    {
                                        value: '0',
                                        label: '只通知一次',
                                    },
                                    {
                                        value: '1',
                                        label: '每天',
                                    },
                                    {
                                        value: '2',
                                        label: '法定工作日',
                                    },
                                    {
                                        value: '3',
                                        label: '周一到周五',
                                    },
                                ]}
                                value={item?.unit}
                                onChange={(value: string) => { onModeChange(value, item?.elementId) }}
                                getPopupContainer={() => document.body}
                            />
                            <div className='process-designer-strategy-push-cycle-regular-item-btn'>
                                <PlusCircleOutlined onClick={() => { onAdd(index) }} />
                                {
                                    cycleData?.length != 1
                                    &&
                                    <CloseCircleOutlined onClick={() => { onDelete(item?.elementId) }} />
                                }
                            </div>
                        </div>
                    )
                })
            }
        </div>
    )
};